package com.example.hello;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;

import androidx.annotation.Nullable;

/**
 * @maker twc
 * @ time 2021/4/20 17:26
 */
public class CallService extends Service {
    private static final String TAG = "CallService";
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG,"服务创建");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG,"服务运行");
        getService();
        return super.onStartCommand(intent, flags, startId);
    }

    private void getService() {
       TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
       tm.listen(new MyListen(),PhoneStateListener.LISTEN_CALL_STATE);
    }

    class MyListen extends PhoneStateListener{
        @Override
        public void onCallStateChanged(int state, String phoneNumber) {
            super.onCallStateChanged(state, phoneNumber);

            switch (state){
                case TelephonyManager.CALL_STATE_IDLE:
                    Log.i("myListener","电话空闲");
                    break;
                case TelephonyManager.CALL_STATE_RINGING:
                    Log.i("myListener","电话响铃");
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    Log.i("myListener","电话通话");
                    break;
            }
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG,"服务销毁");
    }
}
